<template>
  <div class="employee-container">
    <div class="box">
      <div class="left">
        <div class="l-search">
          <el-input
            v-model="form.keyword"
            placeholder="请输入内容"
            prefix-icon="el-icon-search"
            @input="keywordChange"
          />
        </div>
        <div class="l-tree">
          <el-tree
            ref="treeRef"
            :data="data"
            :props="defaultProps"
            highlight-current
            :expand-on-click-node="false"
            node-key="id"
            default-expand-all
            @current-change="currentChange"
          />
        </div>
      </div>
      <div class="right">
        <div class="r-btns">
          <el-row type="flex" class="row-bg" justify="end">
            <el-button type="primary" size="mini" @click="addEmployee">添加成员</el-button>
            <el-button size="mini" @click="showExcelDialog = true">Excel导入</el-button>
            <el-button size="mini" @click="exportExcel">Excel导出</el-button>
          </el-row>
        </div>
        <div class="r-table">
          <el-table
            :data="tableData"
            stripe
            style="width: 100%"
          >
            <el-table-column
              v-slot="{row}"
              prop="staffPhoto"
              label="头像"
              width="120"
            >
              <template v-if="row.staffPhoto">
                <img class="user-avatar" :src="row.staffPhoto" alt="">
              </template>
              <template v-else>
                <span class="img-name">{{ row.username?.charAt(0) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="username"
              label="姓名"
              width="180"
            />
            <el-table-column
              prop="mobile"
              label="手机号"
              width="180"
              sortable
            />
            <el-table-column
              prop="workNumber"
              label="工号"
              width="180"
              sortable
            />
            <el-table-column
              v-slot="{row}"
              prop="formOfEmployment"
              label="聘用形式"
              width="150"
            >
              {{ row.formOfEmployment===1? '正式': '非正式' }}
            </el-table-column>
            <el-table-column
              prop="departmentName"
              label="部门"
              width="180"
            />
            <el-table-column
              prop="timeOfEntry"
              label="入职时间"
              width="150"
              sortable
            />
            <el-table-column
              v-slot="{row}"
              prop="data"
              label="操作"
            >
              <el-button type="text" size="small" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="updateRoeTmp(row.id)">角色</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="popconfirm(row.id)"
              >
                <el-button slot="reference" style="margin-left: 10px;" type="text" size="small">删除</el-button>
              </el-popconfirm>
            </el-table-column>
          </el-table>
        </div>
        <div class="page">
          <el-pagination
            style="text-align: right;"
            layout="total, prev, pager, next"
            :total="total"
            :current-page="form.page"
            :page-size="form.pagesize"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      <ImportExcel :show-excel-dialog.sync="showExcelDialog" @uplad-success="getEmployeeList" />
      <!-- 角色弹窗 -->
      <el-dialog title="添加角色" :visible.sync="showRoleDialog" @close="close">
        <el-form>
          <el-checkbox-group v-model="roleIds">
            <!-- label 这个属性是给后台看的，如果写name的话打印是中文，给id后台才能拿到id，内容的话就用行内 -->
            <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
          <el-form-item label-width="400px">
            <el-button type="primary" size="mini" @click="doAdd">确认</el-button>
            <el-button size="mini" @click="close">取 消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { companyDepartmentRequest } from '@/api/department'
import { transformListToTree } from '@/utils/index.js'
import { getEmployeeListRequest, exportExcelRequest, deleteUserRequest, getEmployeeInfoRequest, assignRolesRequest } from '@/api/employee.js'
import { debounce } from 'lodash-es'
import { roleEnabledListRequest } from '@/api/role'
import ImportExcel from './component/import-excel.vue'
// 这个包能把二进制转换为Excel文件
import { saveAs } from 'file-saver'
export default {
  name: 'Employee',
  components: { ImportExcel },
  data() {
    return {
      form: {
        page: 1,
        pagesize: 5,
        keyword: '',
        departmentId: null
      },
      total: 100,
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      showExcelDialog: false,
      showRoleDialog: false,
      roleIds: [],
      roleList: [],
      currentId: null
    }
  },
  created() {
    this.companyDepartment()
    this.getEmployeeList()
    // 这里是使用lodashi里面的debounce方法，实现节流效果，
    this.keywordChange = debounce(this.keywordChange, 300)
  },
  methods: {
    async companyDepartment() {
      const res = await companyDepartmentRequest()
      this.departmentList = res.data
      // 利用递归来遍历树
      this.data = transformListToTree(res.data, 0)
      this.form.departmentId = this.data[0].id
      this.$nextTick(() => {
        // 默认树形第一个高亮 setCurrentKey这是一个方法默认选择高亮
        this.$refs.treeRef.setCurrentKey(this.form.departmentId)
      })
    },
    close() {
      this.showRoleDialog = false
    },
    async getEmployeeList() {
      const ress = await getEmployeeListRequest(this.form)
      this.tableData = ress.data.rows
      this.total = ress.data.total
    },
    // 点击树的节点发送请求
    currentChange(item) {
      // 小 bug 每次刷新都会从第一页上面找
      this.form.page = 1
      this.form.departmentId = item.id
      this.getEmployeeList()
    },
    handleCurrentChange(val) {
      this.form.page = val
      this.getEmployeeList()
    },
    keywordChange() {
      // 防抖和节流
      // 防抖：只执行最后一次
      // 节流：只执行一次
      this.getEmployeeList()
    },
    // 这是Excel导出
    async exportExcel() {
      const res = await exportExcelRequest()
      saveAs(res, '所有员工信息.xlsx')
      console.log(res)
    },
    async popconfirm(id) {
      await deleteUserRequest(id)
      this.$message.success('删除成功')
      this.getEmployeeList()
    },
    addEmployee() {
      this.$router.push('/employee/detail')
    },
    // 给员工分配权限
    async doAdd() {
      await assignRolesRequest({
        id: this.currentId,
        roleIds: this.roleIds
      })
      this.getEmployeeList()
      this.close()
      this.$message.success('分配权限成功！')
    },
    // 点击获取已启用的角色
    async updateRoeTmp(id) {
      this.currentId = id
      this.showRoleDialog = true
      const res = await roleEnabledListRequest()
      console.log(res)
      this.roleList = res.data
      const res2 = await getEmployeeInfoRequest(id)
      console.log(res2)
      this.roleIds = res2.data.roleIds
    }
  }
}
</script>

<style lang="scss" scoped>
.employee-container{
  min-height: 100vh;
  background-color: #f5f6f8;
  padding: 20px;
  .box{
    display: flex;
  min-height: 50vh;
    background-color: #fff;
    .left{
      flex: 0 0 260px;
      padding: 20px;
      border-right: 1px #e4dada solid;
      // background-color: salmon;
      .l-tree{
        margin-top: 10px;
      }
    }
    .right{
      flex: 1;
      padding: 20px;
      // background-color: palegreen;
      .r-btns{
        margin-bottom: 20px;
      }
      .user-avatar {
          cursor: pointer;
          width: 40px;
          height: 40px;
          border-radius: 10px;
        }
      .img-name{
          display: block;
          width: 40px;
          height: 40px;
          background-color: #00daff;
          text-align: center;
          line-height: 40px;
          border-radius: 50%;
          color: #fff;
          font-weight: 800;
          font-size: 18px;
      }
    }
  }
}
</style>
